package com.biubiushop.socket.netty;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.biubiushop.repository.IEquipmentRepository;
import com.biubiushop.repository.IOrdersRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenjia
 * @date 2019/10/28
 **/
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private static final Log log = LogFactory.get();

    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private ConcurrentHashMap<String, Channel> channelMap;

    private IEquipmentRepository equipmentRepository;

    private IOrdersRepository ordersRepository;

    private StringRedisTemplate stringRedisTemplate;


    public ServerHandler(ThreadPoolTaskExecutor threadPoolTaskExecutor, ConcurrentHashMap<String, Channel> channelMap, IEquipmentRepository equipmentRepository, IOrdersRepository ordersRepository, StringRedisTemplate stringRedisTemplate) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
        this.channelMap = channelMap;
        this.equipmentRepository = equipmentRepository;
        this.ordersRepository = ordersRepository;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("++++++客户端进行读写+++++++++");
        threadPoolTaskExecutor.execute(new NettyReadHandlerThread(ctx, msg, channelMap,
                equipmentRepository, ordersRepository, stringRedisTemplate));
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        ctx.channel().writeAndFlush("Hello, WELCOME TO SERVER!");
        log.info("=======设备接入服务端==========");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx){
        log.info("-----------设备断开链接-----------");
    }

}
